import ApiComm from '../ApiComm'
import { SM3 } from 'gm-crypto'

export default {
  doLogin: (loginNo, password) => {
    const date = new Date()
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    month = month < 10 ? '0' + month : month
    let day = date.getDate()
    day = day < 10 ? '0' + day : day
    let hour = date.getHours()
    hour = hour < 10 ? '0' + hour : hour
    password = SM3.digest(
      SM3.digest(SM3.digest(password, 'utf8', 'hex') + loginNo, 'utf8', 'hex') +
        year +
        month +
        day +
        hour,
      'utf8',
      'hex'
    )
    return ApiComm.$http.post(
      '/server/token',
      {
        grant_type: 'user_password',
        client_id: ApiComm.$store.state.app.appInfo.appId,
        client_secret: ApiComm.$store.state.app.appInfo.appSecret,
        username: loginNo,
        password: password
      },
      {
        headers: {
          Process401: 'false',
          Process403: 'false'
        }
      }
    )
  },
  doLogOut: () => {
    return ApiComm.$http.post('/server/logout')
  },
  getUserInfo: () => {
    return ApiComm.$http.get('/server/user-info')
  },
  updateUserInfo: (userInfo) => {
    if (userInfo.oldPassword) {
      userInfo.oldPassword = SM3.digest(
        SM3.digest(userInfo.oldPassword, 'utf8', 'hex') +
          ApiComm.$store.state.app.user.userInfo.loginNo,
        'utf8',
        'hex'
      )
    }
    if (userInfo.password) {
      userInfo.password = SM3.digest(
        SM3.digest(userInfo.password, 'utf8', 'hex') +
          ApiComm.$store.state.app.user.userInfo.loginNo,
        'utf8',
        'hex'
      )
    }
    return ApiComm.$http.patch('/server/user-info', userInfo)
  },
  getOnlineInfo: () => {
    return ApiComm.$http.get('/server/online-info')
  }
}
